package cn.zmall.sso.service.impl;


import cn.zmall.common.exception.ZmallException;
import cn.zmall.common.jedis.JedisClient;
import cn.zmall.common.utils.IDUtil;
import cn.zmall.manager.dto.OrderDto;
import cn.zmall.manager.dto.ThanksDto;
import cn.zmall.manager.dto.front.*;
import cn.zmall.manager.mapper.*;
import cn.zmall.manager.pojo.*;
import cn.zmall.sso.service.OrderService;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author cxy
 * @Date 2020/11/5 17:06
 * @Version 1.0
 */

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    private final static Logger log = LoggerFactory.getLogger(OrderService.class);

    private BigDecimal balance = new BigDecimal(0);//每件商品的总额
    private BigDecimal Totalbalance = new BigDecimal(0);//购买商品的总额

    @Autowired
    private TbOrderMapper tbOrderMapper;//订单
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;//商品
    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;//购物记录
    @Autowired
    private TbMemberMapper tbMemberMapper;//用户
    @Autowired
    private TbThanksMapper tbThanksMapper;
    @Autowired
    private TbAddressMapper tbAddressMapper;//用户地址
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("Order")
    private String ORDER_PRE;
    @Value("1500")
    private Integer ORDER_EXPIRE;
    @Value("Cart")
    private String CART_PRE;

    //创建订单
    //return值 -1用户余额为空 -2余额不足 -3库存不足 -4未选择收货地址
    @Override
    public Long placeOrder(OrderDto orderDto) {
        TbOrder tbOrder = new TbOrder();
        TbThanks tbThanks = new TbThanks();
        TbOrderShipping tbOrderShipping = new TbOrderShipping();

//        if (getUserUnpayment(Long.valueOf(orderDto.getUserId())) != null) {
//            return Long.valueOf(-3);
//        }
        //status 状态 0未付款 1已付款 2未发货 3已发货 4交易成功 5交易关闭 6交易失败
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(Long.valueOf(orderDto.getUserId()));
        if (tbMember == null) {
            throw new ZmallException("获取账户失败");
        }
        TbAddress tbAddress = tbAddressMapper.selectByPrimaryKey(Long.valueOf(orderDto.getAddressId()));
        if (tbAddress == null) {
            return Long.valueOf(-4);
        }
        //随机生成订单号
        Long orderId = IDUtil.getRandomId();

        //订单信息
        tbOrder.setOrderId(String.valueOf(orderId));
        tbOrder.setPaymentType(1);
        tbOrder.setUserId(Long.valueOf(orderDto.getUserId()));
        tbOrder.setBuyerNick(tbMember.getUsername());
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());

        //购物记录
        tbOrderShipping.setOrderId(String.valueOf(orderId));
        tbOrderShipping.setReceiverName(orderDto.getUserName());
        tbOrderShipping.setReceiverAddress(tbAddress.getStreetName());
        tbOrderShipping.setReceiverPhone(tbMember.getPhone());
        tbOrderShipping.setCreated(new Date());
        tbOrderShipping.setUpdated(new Date());

        //商品信息
        List<CartProduct> list = orderDto.getCartProducts();
        for (CartProduct cartProduct : list) {
            TbOrderItem tbOrderItem = new TbOrderItem();
            long id = IDUtil.getRandomId();
            tbOrderItem.setId(String.valueOf(id));
            TbItem item = tbItemMapper.selectByPrimaryKey(cartProduct.getProductId());
            //删除item库存
            if (item == null) {
                throw new ZmallException("请输入正确的商品ID");
            }
            if (item.getNum() < cartProduct.getProductNum()) {
                return Long.valueOf(-3);
            }
            item.setNum((int) (item.getNum() - cartProduct.getProductNum()));
            updateTbItem(item);

            tbOrderItem.setItemId(String.valueOf(cartProduct.getProductId()));
            tbOrderItem.setOrderId(String.valueOf(orderId));
            tbOrderItem.setNum(Math.toIntExact(cartProduct.getProductNum()));
            tbOrderItem.setPrice(item.getPrice());
            tbOrderItem.setTitle(item.getTitle());
            tbOrderItem.setPicPath(item.getImage());

            //每件商品的总额
            balance = item.getPrice().multiply(BigDecimal.valueOf(cartProduct.getProductNum()));
            //订单总额
            Totalbalance = Totalbalance.add(balance);
            tbOrderItem.setTotalFee(balance);
            tbOrder.setPayment(Totalbalance);
            tbThanks.setMoney(Totalbalance);
            if (tbMember.getBalance().subtract(balance).compareTo(new BigDecimal(0)) != 1) {
                return Long.valueOf(-2);
            }
            tbMember.setBalance(tbMember.getBalance().subtract(balance));
            if (tbOrderItemMapper.insert(tbOrderItem) != 1) {
                throw new ZmallException("生成商品信息失败");
            }

            //删除购物车中含该订单的商品
            try {
                List<String> jsonList = jedisClient.hvals(CART_PRE + ":" + orderDto.getUserId());
                for (String test : jsonList) {
                    CartProduct goods = new Gson().fromJson(test, CartProduct.class);
                    if (goods.getProductId().equals(cartProduct.getProductId())) {
                        jedisClient.hdel(CART_PRE + ":" + orderDto.getUserId(), goods.getProductId() + "");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //付款信息
        tbThanks.setUsername(tbMember.getUsername());
        tbThanks.setEmail(tbMember.getEmail());
        tbThanks.setUserId(tbOrder.getUserId());
        tbThanks.setOrderId(String.valueOf(orderId));
        tbThanks.setDate(new Date());
        tbThanks.setPayType(orderDto.getPayType());

        //创建付款信息
        if (!orderDto.isPayFlag()) {
            tbOrder.setStatus(0);
            //将未付款的订单信息缓存在redis
            OrderRedis orderRedis = new OrderRedis();
            orderRedis.setAddressId(orderDto.getAddressId());
            orderRedis.setOrderId(orderId);
            orderRedis.setOrderTotal(Totalbalance);
            orderRedis.setUsername(tbMember.getUsername());
            orderRedis.setPrice(balance);
            orderRedis.setNum(orderDto.getCartProducts().get(0).getProductNum().intValue());
            jedisClient.set(ORDER_PRE + ":" + tbMember.getId(), new Gson().toJson(orderRedis));
            jedisClient.expire(ORDER_PRE + ":" + tbMember.getId(), ORDER_EXPIRE);
            //创建订单
            creatOrder(tbOrder);
            //创建购物信息
            creatOrderShopping(tbOrderShipping);
        } else {
            tbOrder.setStatus(1);
            tbOrder.setPaymentTime(new Date());
            tbThanks.setState(1);
            //创建订单
            creatOrder(tbOrder);
            //创建购物信息
            creatOrderShopping(tbOrderShipping);
            //创建付款信息
            creatTbThanks(tbThanks);
            //更新用户余额
            updateTbMenber(tbMember);
        }
        return orderId;
    }

    //通过Id查询订单
    @Override
    public OrderList getOrder(Long orderId) {
        OrderList orderList = new OrderList();
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(String.valueOf(orderId));
        if (tbOrder == null) {
            return null;
        }
        //TbOrder
        orderList.setTbOrder(tbOrder);
        //TbOrderShipping
        TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(tbOrder.getOrderId());
        orderList.setTbOrderShipping(tbOrderShipping);
        //TbOrderItem
        TbOrderItemExample tbOrderItemExample = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = tbOrderItemExample.createCriteria();
        criteria.andOrderIdEqualTo(String.valueOf(orderId));
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(tbOrderItemExample);
        orderList.setTbOrderItems(tbOrderItems);

        return orderList;
    }

    //取消订单
    @Override
    public int cancleOrder(Long orderId) {
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(String.valueOf(orderId));
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(Long.valueOf(tbOrder.getUserId()));
        TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(String.valueOf(orderId));
        if (tbOrder == null) {
            return Integer.parseInt(null);
        }
        if (tbOrderShipping == null) {
            return Integer.parseInt(null);
        }
        //用户余额返回
        BigDecimal payment = tbOrder.getPayment();
        BigDecimal balance = tbMember.getBalance();
        tbMember.setBalance(balance.add(payment));

        tbOrder.setStatus(5);//交易关闭
        tbOrder.setUpdateTime(new Date());
        tbOrder.setCloseTime(new Date());
        tbOrder.setEndTime(new Date());
        tbOrderShipping.setUpdated(new Date());
        if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
            return -1;
        }
        if (tbOrderShippingMapper.updateByPrimaryKey(tbOrderShipping) != 1) {
            return -1;
        }
        updateTbMenber(tbMember);
        return 1;
    }

    //删除订单
    @Override
    public int deleteOrder(Long orderId) {
        if (tbOrderMapper.deleteByPrimaryKey(String.valueOf(orderId)) != 1) {
            return -1;
        }

        return 1;
    }

    //删除购物记录
    @Override
    public int deleteOrderShopping(Long orderId) {
        if (tbOrderShippingMapper.deleteByPrimaryKey(String.valueOf(orderId)) != 1) {
            return -1;
        }
        return 1;
    }

    //支付订单
    @Override
    public int payOrder(ThanksDto thanksDto) {
        String json = jedisClient.get(ORDER_PRE + ":" + thanksDto.getId());
        OrderRedis orderRedis = new Gson().fromJson(json, OrderRedis.class);

        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(Long.valueOf(thanksDto.getId()));
        TbThanks tbThanks = new TbThanks();
        if (tbMember != null) {
            tbThanks.setUsername(tbMember.getUsername());
        }
        tbThanks.setDate(new Date());
        tbThanks.setState(1);
        tbThanks.setUserId(Long.valueOf(thanksDto.getId()));
        tbThanks.setUsername(orderRedis.getUsername());
        tbThanks.setEmail(tbMember.getEmail());
        tbThanks.setOrderId(String.valueOf(orderRedis.getOrderId()));
        tbThanks.setInfo(thanksDto.getInfo());
        tbThanks.setPayType(thanksDto.getPayType());
        BigDecimal tbMemberBalance = tbMember.getBalance();//用户余额
        BigDecimal tbThanksMoney = new BigDecimal(String.valueOf(orderRedis.getOrderTotal()));
        BigDecimal flag = new BigDecimal(0);
        BigDecimal balance = tbMemberBalance.subtract(tbThanksMoney);//余额
        if (balance.compareTo(flag) != 1) {
            return -2;
        }
        tbThanks.setMoney(tbThanksMoney);
        tbMember.setBalance(tbMemberBalance.subtract(tbThanksMoney));
        updateTbMenber(tbMember);
        creatTbThanks(tbThanks);
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(String.valueOf(tbThanks.getOrderId()));
        tbOrder.setStatus(1);
        tbOrder.setUpdateTime(new Date());
        tbOrder.setPaymentTime(new Date());
        if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
            return -1;
        }
        //删除缓存
        jedisClient.del(ORDER_PRE + ":" + tbMember.getId());

        return 1;
    }

    //用户充值
    @Override
    public int UserCharge(Long userId, BigDecimal money) {
        TbMember member = tbMemberMapper.selectByPrimaryKey(userId);
        if (member == null) {
            throw new ZmallException("查询不到改用户");
        }
        if (member.getBalance() == null) {
            member.setBalance(new BigDecimal(0));
        }
        BigDecimal memberBalance = member.getBalance();
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(memberBalance.add(money)));
        member.setBalance(bigDecimal);

        int result = tbMemberMapper.updateByPrimaryKey(member);
        if (result != 1) {
            return -1;
        }
        return 1;
    }

    //用户所有订单
    @Override
    public List<TbOrder> getUserOrderList(Long userId) {
        TbOrderExample tbOrderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);

        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(tbOrderExample);

        return tbOrders;
    }

    //用户未支付订单
    @Override
    public OrderRedis getUserUnpayment(Long userId) {
        String json = jedisClient.get(ORDER_PRE + ":" + userId);
        if (json != null) {
            OrderRedis orderRedis = new Gson().fromJson(json, OrderRedis.class);
            return orderRedis;
        }
        return null;
    }

    //用户已支付订单
    @Override
    public List<TbOrder> getAccountPaid(Long userId) {
        List<TbOrder> orderList = new ArrayList<>();

        TbOrderExample tbOrderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(tbOrderExample);
        for (int i = 0; i < tbOrders.size(); i++) {
            if (tbOrders.get(i).getStatus() == 1) {
                orderList.add(tbOrders.get(i));
            }
        }

        return orderList;
    }

    @Override
    public List<TbOrder> getOrderByStatus(Long userId, Integer status) {
        List<TbOrder> orderList = new ArrayList<>();

        TbOrderExample tbOrderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(tbOrderExample);
        for (int i = 0; i < tbOrders.size(); i++) {
            if (tbOrders.get(i).getStatus() == status) {
                orderList.add(tbOrders.get(i));
            }
        }
        return tbOrders;
    }

    //创建订单信息
    public int creatOrder(TbOrder tbOrder) {
        if (tbOrderMapper.insert(tbOrder) != 1) {
            return -1;
        }
        return 1;
    }

    //创建购物信息
    public int creatOrderShopping(TbOrderShipping tbOrderShipping) {
        if (tbOrderShippingMapper.insert(tbOrderShipping) != 1) {
            return -1;
        }
        return 1;
    }

    //创建付款信息
    public int creatTbThanks(TbThanks tbThanks) {
        if (tbThanksMapper.insert(tbThanks) != 1) {
            return -1;
        }
        return 1;
    }

    //更新用户余额
    public int updateTbMenber(TbMember tbMember) {
        if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
            return -1;
        }
        return 1;
    }

    //更新用户余额
    public int updateTbItem(TbItem tbItem) {
        if (tbItemMapper.updateByPrimaryKey(tbItem) != 1) {
            return -1;
        }
        return 1;
    }
}
